#!/bin/sh

DAEMON=wsd_simple_server
PRUDYNT_CONFIG=/etc/prudynt.json
ONVIF_CONFIG=/etc/onvif.json
ONVIF_WEBUI_CONF=/etc/webui/onvif.conf

. /usr/share/common

iface="$(iface_default)"

model=$(awk -F '=' '/^IMAGE_ID=/ {print $2}' $OS_RELEASE_FILE)

# extract iface for daemon from onvif.json
DAEMON_ARGS="-i $iface -x http://%s/onvif/device_service -m $model -n thingino -p /run/$DAEMON_SHORT.pid"

# read web config, create if missing
[ -d $(dirname $ONVIF_WEBUI_CONF) ] || mkdir -p $(dirname $ONVIF_WEBUI_CONF)
[ -f $ONVIF_WEBUI_CONF ] || touch $ONVIF_WEBUI_CONF
. $ONVIF_WEBUI_CONF

start() {
	echo_title "Starting ONVIF discovery"

	if ! is_gateway_reachable; then
		echo_error "Disabled"
		exit 1
	fi

	if is_streamer_disabled; then
		echo_error "Streamer disabled"
		exit 1
	fi

	start_daemon

	tmpfile=$(mktemp -u)
	cp $ONVIF_CONFIG $tmpfile
	jct $tmpfile set camera.model "$model"
	jct $tmpfile set camera.hardware_id "ingenic_$SOC_MODEL"
	jct $tmpfile set camera.serial_num "$(fw_printenv -n ethaddr | sed 's/://g')"
	jct $tmpfile set camera.firmware_ver "$(awk -F'[=,"]' '/^BUILD_ID/{print $3 $4}' /etc/os-release)"

	jct $tmpfile set server.ifs "$iface"
	jct $tmpfile set server.username "$(jct $PRUDYNT_CONFIG get rtsp.username)"
	jct $tmpfile set server.password "$(jct $PRUDYNT_CONFIG get rtsp.password)"

	# conditional PTZ config
	if [ -n "$gpio_motor_h" ] || [ -n "$motor" ]; then
		jct $tmpfile set ptz.enable 1
		jct $tmpfile set ptz.max_step_x "$motor_maxstep_h"
		jct $tmpfile set ptz.max_step_y "$motor_maxstep_v"
		jct $tmpfile set ptz.move_right "/bin/motors -d h -x $motor_maxstep_h"
		jct $tmpfile set ptz.move_down "/bin/motors -d h -y $motor_maxstep_v"
	fi
	mv $tmpfile $ONVIF_CONFIG
}

stop() {
	echo_title "Stopping ONVIF discovery"

	stop_daemon
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

exit 0
